/**
 * Created by zaife_000 on 2014/5/18.
 */
package com.familybox.app.view.mediators {

    import com.familybox.app.services.IAuthService;
    import com.familybox.app.view.components.LoginView;
    import com.familybox.app.view.components.MainView;

    import flash.data.EncryptedLocalStore;
    import flash.utils.ByteArray;
    import org.robotlegs.mvcs.Mediator;
    import org.robotlegs.oil.async.Promise;

    public class MainMediator extends Mediator {

        [Inject]
        public var mainView:MainView;

        [Inject]
        public var authService:IAuthService;

        public function MainMediator() {
        }

        override public function onRegister():void{
            loading();
        }

        private function loading():void{

            var storedValue:ByteArray = EncryptedLocalStore.getItem('token');
            if (storedValue!=null) {
                trace(token);
                var token:String = storedValue.readUTFBytes(storedValue.length);
                var result:Promise= authService.validToken(token);
                result.addResultHandler(validTokenResultHandler)
                        .addErrorHandler(validTokenResultHandler)
                        .addProgressHandler(validTokenResultHandler);
            }
            else {
                trace("No stored data found ");
                showLoginView();
            }
        }

        private function validTokenResultHandler(p:Promise):void {

            if(p.status==Promise.COMPLETE){
                trace(p.result);
                var result:Object=p.result;

                var data:Object=result.data;

                if(data.success==true){

                }
                else{
                    showLoginView();
                }
            }
        }

        private function showLoginView():void
        {
            mainView.removeAllElements();
            mainView.addElement(new LoginView());
        }

        private function showContentView():void
        {

        }
    }
}
